package com.xinwei.linearExercise;

import java.util.Arrays;

/**
 * 循环队列
 * 使用动态数据实现,左边队头，右边队尾，从队尾入队，从队头出队
 */
public class CircleQueue<E> {
    private Integer front = 0;
    private Integer size = 0;
    private E[] elements;
    private static final Integer DEFAULT_CAPACITY = 10;
    public CircleQueue(){
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void enQueue(E element) {
        // 循环可以使用取模实现
        ensureCapacity();
        elements[(front + size) % elements.length] = element;
        size++;
    }

    private void ensureCapacity() {
        int oldCapacity = elements.length;
        if (size + 1 > oldCapacity) {
            // 这里oldCapacity >> 1相当于oldCapacity/2
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            E[] newElements = (E[]) new Object[newCapacity];
            for (int i = 0; i < size; i++) {
                newElements[i] = elements[(front + i) % elements.length];
            }
            front = 0;
            elements = newElements;
        }
    }

    public E deQueue() {
        E frontElement = elements[front];
        elements[front] = null;
        front = (front + 1) % elements.length;
        size--;
        return frontElement;
    }

    public E front() {
        return elements[front];
    }

    @Override
    public String toString() {
        return "CircleQueue{" +
                "front=" + front +
                ", size=" + size +
                ", elements=" + Arrays.toString(elements) +
                '}';
    }
}
